<!-- src/views/certificate/index.vue -->
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <!-- 账号/用户账号 -->
      <el-form-item label="账号：" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入账号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 开具日期范围 -->
      <el-form-item label="开具日期：" prop="issueDateRange">
        <el-date-picker
          v-model="queryParams.issueDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          size="small"
        />
      </el-form-item>

      <!-- 主体名称 -->
      <el-form-item label="主体名称：" prop="producerName">
        <el-input
          v-model="queryParams.producerName"
          placeholder="请输入主体名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 产品名称 -->
      <el-form-item label="产品名称：" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入产品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 检验机构 -->
      <el-form-item label="检验机构：" prop="inspectionAgency">
        <el-input
          v-model="queryParams.inspectionAgency"
          placeholder="请输入检验机构"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- 合格方式 -->
      <el-form-item label="合格方式：" prop="qualifiedMethod">
        <el-select v-model="queryParams.qualifiedMethod" placeholder="请选择" clearable size="small">
          <el-option label="所有" value="" />
          <el-option label="委托检测" value="委托检测" />
          <el-option label="自我检测" value="自我检测" />
          <el-option label="内部质量控制" value="内部质量控制" />
          <el-option label="自我承诺" value="自我承诺" />
        </el-select>
      </el-form-item>
      <!-- 合格证编号 -->
      <el-form-item label="合格证编号：" prop="certificateNo">
        <el-input
          v-model="queryParams.certificateNo"
          placeholder="请输入合格证编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button type="text" size="mini" @click="toggleSearch">
          {{ showExtraSearch ? '收起搜索' : '展开搜索' }}
          <i :class="showExtraSearch ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
        </el-button>
      </el-form-item>

      <!-- 扩展搜索条件 -->
      <div v-show="showExtraSearch" style="width: 100%;">
        <el-form-item label="数据来源：" prop="dataSource">
          <el-select v-model="queryParams.dataSource" placeholder="请选择数据来源" clearable size="small">
            <el-option label="所有" value="" />
            <el-option label="小程序端" value="mini_program" />
            <el-option label="PC端" value="pc" />
          </el-select>
        </el-form-item>
      </div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['certificate:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['certificate:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['certificate:delete']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['certificate:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="certificateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="主体名称" align="center" prop="companyName" />
<!--      <el-table-column label="法人姓名" align="center" prop="legalPerson" />-->
      <el-table-column label="合格证编号" align="center" prop="certificateNo" />
      <el-table-column label="产品名称" align="center" prop="productName" />
      <el-table-column label="产品重量" align="center" prop="productWeight">
        <template slot-scope="scope">
          <span>{{ scope.row.productWeight }} {{ scope.row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="合格方式" align="center" prop="qualifiedMethod" />
      <el-table-column label="检验机构" align="center" prop="inspectionAgency" />
      <el-table-column label="检测报告" align="center">
        <template slot-scope="scope">
          <el-link
            v-if="scope.row.inspectionReport"
            @click="previewReport(scope.row.inspectionReport)"
            :underline="false"
          >
            <i class="el-icon-document" style="font-size: 20px;"></i>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="开具日期" align="center" prop="issueDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.issueDate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="打印次数" align="center" prop="printTimes" />
      <el-table-column label="扫描次数" align="center" prop="scanTimes" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['certificate:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['certificate:delete']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="主体名称" prop="producerName">
              <el-input v-model="form.producerName" placeholder="请输入主体名称" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="法人姓名" prop="legalPerson">-->
<!--              <el-input v-model="form.legalPerson" placeholder="请输入法人姓名" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="合格证编号" prop="certificateNo">
              <el-input v-model="form.certificateNo" placeholder="请输入合格证编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开具日期" prop="issueDate">
              <el-date-picker
                v-model="form.issueDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择开具日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品重量" prop="productWeight">
              <el-input v-model.number="form.productWeight" placeholder="请输入产品重量">
                <template slot="append">{{ form.unit || '公斤' }}</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select v-model="form.unit" placeholder="请选择单位">
                <el-option label="公斤" value="公斤"></el-option>
                <el-option label="吨" value="吨"></el-option>
                <el-option label="件" value="件"></el-option>
                <el-option label="箱" value="箱"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合格方式" prop="qualifiedMethod">
              <el-select v-model="form.qualifiedMethod" placeholder="请选择合格方式">
                <el-option label="委托检测" value="委托检测"></el-option>
                <el-option label="自我检测" value="自我检测"></el-option>
                <el-option label="内部质量控制" value="内部质量控制"></el-option>
                <el-option label="自我承诺" value="自我承诺"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="检验机构" prop="inspectionAgency">
              <el-input v-model="form.inspectionAgency" placeholder="请输入检验机构" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="检测报告" prop="inspectionReport">
              <el-input v-model="form.inspectionReport" placeholder="请输入检测报告链接" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog title="合格证详情" :visible.sync="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ID">{{ detailForm.id }}</el-descriptions-item>
        <el-descriptions-item label="主体名称">{{ detailForm.producerName }}</el-descriptions-item>
<!--        <el-descriptions-item label="法人姓名">{{ detailForm.legalPerson }}</el-descriptions-item>-->
        <el-descriptions-item label="地址">{{ detailForm.address }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailForm.phone }}</el-descriptions-item>
        <el-descriptions-item label="合格证编号">{{ detailForm.certificateNo }}</el-descriptions-item>
        <el-descriptions-item label="开具日期">{{ parseTime(detailForm.issueDate) }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ detailForm.productName }}</el-descriptions-item>
        <el-descriptions-item label="产品重量">{{ detailForm.productWeight }} {{ detailForm.unit }}</el-descriptions-item>
        <el-descriptions-item label="合格方式">{{ detailForm.qualifiedMethod }}</el-descriptions-item>
        <el-descriptions-item label="检验机构">{{ detailForm.inspectionAgency }}</el-descriptions-item>
        <el-descriptions-item label="检测报告">
          <el-link
            v-if="detailForm.inspectionReport"
            @click="previewReport(detailForm.inspectionReport)"
            :underline="false"
          >
            {{ detailForm.inspectionReport }}
          </el-link>
          <span v-else>无</span>
        </el-descriptions-item>
        <el-descriptions-item label="打印次数">{{ detailForm.printTimes }}</el-descriptions-item>
        <el-descriptions-item label="扫描次数">{{ detailForm.scanTimes }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detailForm.remark }}</el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 预览检测报告对话框 -->
    <el-dialog :title="previewTitle" :visible.sync="previewOpen" width="800px" append-to-body>
      <div v-if="isImage" style="text-align: center;">
        <img :src="previewUrl" style="max-width: 100%; max-height: 600px;" />
      </div>
      <div v-else-if="isPdf">
        <iframe :src="previewUrl" width="100%" height="600px"></iframe>
      </div>
      <div v-else>
        <p>不支持预览的文件类型</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="previewOpen = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCertificate, getCertificate, addCertificate, updateCertificate, delCertificate, exportCertificate } from "@/api/nongjt/certificate/certificate";
import { parseTime } from "@/utils/ruoyi";

export default {
  name: "Certificate",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 显示扩展搜索条件
      showExtraSearch: false,
      // 总条数
      total: 0,
      // 合格证表格数据
      certificateList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        issueDateRange: [],
        producerName: null,
        productName: null,
        inspectionAgency: null,
        qualifiedMethod: null,
        province: null,
        city: null,
        county: null,
        town: null,
        certificateNo: null,
        dataSource: null
      },
      // 省份选项（模拟数据）
      provinceOptions: ['四川省', '广东省', '江苏省', '浙江省', '山东省'],
      // 城市选项（模拟数据）
      cityOptions: ['成都市', '绵阳市', '德阳市', '南充市', '宜宾市'],
      // 区县选项（模拟数据）
      countyOptions: ['高新区', '郫都区', '金牛区', '锦江区', '青羊区'],
      // 乡镇选项（模拟数据）
      townOptions: ['新湖街道', '合作街道', '西园街道', '中和街道'],
      // 用户类型判断
      isAdmin: this.$store.getters.roles.includes('admin'),
      isSupervisor: this.$store.getters.roles.includes('supervisor'),
      // 弹窗相关
      open: false,
      detailOpen: false,
      dialogTitle: "",
      // 表单参数
      form: {},
      detailForm: {},
      // 表单校验
      rules: {
        producerName: [
          { required: true, message: "主体名称不能为空", trigger: "blur" }
        ],
        // legalPerson: [
        //   { required: true, message: "法人姓名不能为空", trigger: "blur" }
        // ],
        certificateNo: [
          { required: true, message: "合格证编号不能为空", trigger: "blur" }
        ],
        issueDate: [
          { required: true, message: "开具日期不能为空", trigger: "change" }
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ],
        productWeight: [
          { required: true, message: "产品重量不能为空", trigger: "blur" },
          { type: "number", message: "产品重量必须为数字值" }
        ],
        unit: [
          { required: true, message: "单位不能为空", trigger: "change" }
        ],
        qualifiedMethod: [
          { required: true, message: "合格方式不能为空", trigger: "change" }
        ]
      },
      // 预览对话框
      previewOpen: false,
      previewTitle: "",
      previewUrl: "",
      isImage: false,
      isPdf: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询合格证列表 */
    getList() {
      this.loading = true;
      // 处理日期范围查询参数
      const params = {
        ...this.queryParams,
        startDate: this.queryParams.issueDateRange ? this.queryParams.issueDateRange[0] : null,
        endDate: this.queryParams.issueDateRange ? this.queryParams.issueDateRange[1] : null
      };

      // 删除不需要的参数
      delete params.issueDateRange;

      listCertificate(params).then(response => {
        this.certificateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    /** 切换扩展搜索 */
    toggleSearch() {
      this.showExtraSearch = !this.showExtraSearch;
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.issueDateRange = [];
      this.handleQuery();
    },

    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.dialogTitle = "添加合格证";
      this.open = true;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids[0];
      getCertificate(id).then(response => {
        this.form = response.data;
        this.dialogTitle = "修改合格证";
        this.open = true;
      });
    },

    /** 查看按钮操作 */
    handleView(row) {
      getCertificate(row.id).then(response => {
        this.detailForm = response.data;
        this.detailOpen = true;
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateCertificate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCertificate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除合格证编号为"' + ids + '"的数据项？').then(function() {
        return delCertificate(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      const params = {
        ...this.queryParams,
        startDate: this.queryParams.issueDateRange ? this.queryParams.issueDateRange[0] : null,
        endDate: this.queryParams.issueDateRange ? this.queryParams.issueDateRange[1] : null
      };
      delete params.issueDateRange;

      this.$modal.confirm('是否确认导出所有合格证数据？').then(() => {
        return exportCertificate(params);
      }).then(response => {
        this.download(response.msg);
      }).catch(() => {});
    },

    /** 预览检测报告 */
    previewReport(fileUrl) {
      this.previewUrl = fileUrl;
      this.isImage = /\.(png|jpg|jpeg|gif|bmp|webp)$/i.test(fileUrl);
      this.isPdf = /\.pdf$/i.test(fileUrl);
      this.previewTitle = this.isImage ? "检测报告图片" :
        this.isPdf ? "检测报告PDF" : "检测报告文件";
      this.previewOpen = true;
    },

    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        producerName: null,
        legalPerson: null,
        address: null,
        phone: null,
        certificateNo: null,
        issueDate: null,
        productName: null,
        productWeight: null,
        unit: "公斤",
        qualifiedMethod: null,
        inspectionAgency: null,
        inspectionReport: null,
        remark: null
      };
      this.resetForm("form");
    },

    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },

    /** 重置表单 */
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },

    /** 时间格式化 */
    parseTime
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
